//
//  WDOriImageCell.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/28.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDOriImageCell.h"

static CGFloat maxScale = 3.0;
static CGFloat minScale = 1.0;

@interface WDOriImageCell () <UIScrollViewDelegate, UIActionSheetDelegate>

/** 图片 */
@property (nonatomic, strong) UIImageView *imageView;
/** scrollView */
@property (nonatomic, strong) UIScrollView *scrollView;
/** 当前的倍数 */
@property (assign, nonatomic) CGFloat currentScale;

@end

@implementation WDOriImageCell

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        
        scrollView.frame = [UIScreen mainScreen].bounds;
        
        scrollView.delegate = self;
        
        //最大（最小）缩放比
        scrollView.minimumZoomScale = minScale;
        
        scrollView.maximumZoomScale = maxScale;
        
        self.currentScale = 1.0;
        
        //去掉水平、竖直方向滚动条
        scrollView.showsVerticalScrollIndicator = NO;
        
        scrollView.showsHorizontalScrollIndicator = NO;
        
        [self.contentView addSubview:scrollView];
        
        self.scrollView = scrollView;
        
        
        UIImageView *imageView = [[UIImageView alloc] init];
        
        imageView.userInteractionEnabled = YES;
        
        //添加手势(双击)
        UITapGestureRecognizer *tapTwo = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwo)];
        
        [tapTwo setNumberOfTapsRequired:2];
        
        [imageView addGestureRecognizer:tapTwo];
        
        //添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        longPress.minimumPressDuration = 1.0;
        
        [imageView addGestureRecognizer:longPress];
        
        //imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        [scrollView addSubview:imageView];
        
        self.imageView = imageView;
        
        
    }
    return self;
}

- (void)setImageURL:(NSString *)imageURL
{
    _imageURL = imageURL;
    
    if ([imageURL containsString:@"http"]) {
        __weak typeof (self)weakSelf = self;
        
        [SVProgressHUD show];
        
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:imageURL] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            [SVProgressHUD dismiss];
            
            CGFloat solW = [UIScreen mainScreen].bounds.size.width / image.size.width;
            CGFloat solH =  [UIScreen mainScreen].bounds.size.height / image.size.height;
            CGFloat imgW;
            CGFloat imgH;
            CGFloat imgX;
            CGFloat imgY;
            
            if (solH < solW) {//高先到边缘
                
                imgW = image.size.width * solH;
                
                imgH = [UIScreen mainScreen].bounds.size.height;
                
                imgX = [UIScreen mainScreen].bounds.size.width /2 - imgW / 2;
                
                imgY = 0;
                
            } else {//宽先到边缘
                
                imgW = [UIScreen mainScreen].bounds.size.width;
                
                imgH = image.size.height * solW;
                
                imgY = [UIScreen mainScreen].bounds.size.height /2 - imgH / 2;
                
                imgX = 0;
                
            }
            
            weakSelf.imageView.frame = CGRectMake(imgX, imgY, imgW, imgH);
            
        }];
    } else {
        
        UIImage *image = [UIImage imageWithContentsOfFile:[WDCachePath stringByAppendingPathComponent:imageURL]];
        
        CGFloat solW = [UIScreen mainScreen].bounds.size.width / image.size.width;
        CGFloat solH =  [UIScreen mainScreen].bounds.size.height / image.size.height;
        CGFloat imgW;
        CGFloat imgH;
        CGFloat imgX;
        CGFloat imgY;
        
        if (solH < solW) {//高先到边缘
            
            imgW = image.size.width * solH;
            
            imgH = [UIScreen mainScreen].bounds.size.height;
            
            imgX = [UIScreen mainScreen].bounds.size.width /2 - imgW / 2;
            
            imgY = 0;
            
        } else {//宽先到边缘
            
            imgW = [UIScreen mainScreen].bounds.size.width;
            
            imgH = image.size.height * solW;
            
            imgY = [UIScreen mainScreen].bounds.size.height /2 - imgH / 2;
            
            imgX = 0;
            
        }
        
        self.imageView.image = image;
        
        self.imageView.frame = CGRectMake(imgX, imgY, imgW, imgH);
        
        
    }
}

#pragma mark - 手势点击
- (void)tapTwo
{
    //如果放大最大倍数，就缩小到1倍，如果是最小倍数，就放大到最大倍数
    //当前倍数等于最大放大倍数
    //双击默认为缩小到原图
    if (self.currentScale == maxScale) {
        
        self.currentScale = minScale;
        
        [self.scrollView setZoomScale:self.currentScale animated:YES];
        
        return;
    }
    
    //当前等于最小放大倍数
    //双击默认为放大到最大倍数
    if (self.currentScale == minScale) {
        
        self.currentScale = maxScale;
        
        [self.scrollView setZoomScale:self.currentScale animated:YES];
        
        return;
    }
    
    CGFloat aveScale = minScale + (maxScale - minScale) / 2.0;//中间倍数
    
    //当前倍数大于平均倍数
    //双击默认为放大最大倍数
    if (self.currentScale >= aveScale) {
        
        self.currentScale= maxScale;
        
        [self.scrollView setZoomScale:self.currentScale animated:YES];
        
        return;
    }
    
    //当前倍数小于平均倍数
    //双击默认为放大到最小倍数
    if (self.currentScale < aveScale) {
        self.currentScale = minScale;
        [self.scrollView setZoomScale:self.currentScale animated:YES];
        return;
    }
}

- (void)longPress:(id)sender
{
    UILongPressGestureRecognizer *longPress = sender;
    
    if (longPress.state == UIGestureRecognizerStateBegan)
        
    {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存图片", nil];
        
        UIView *window = [UIApplication sharedApplication].keyWindow;
        [sheet showInView:window];
    }
}

#pragma mark - <UIActionSheetDelegate>
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {//保存到相册
        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    if(!error)
    {
        //保存成功
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD showSuccessWithStatus:@"图片已保存"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD dismiss];
                
            });
            
        });
    }
    else
    {
        //保存失败
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD showErrorWithStatus:@"图片保存失败"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD dismiss];
                
            });
            
        });
    }
    
}

#pragma mark - <UIScrollViewDelegate>
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGSize boundsSize = scrollView.bounds.size;
    CGRect imgFrame = self.imageView.frame;
    
    CGSize contentSize = scrollView.contentSize;
    
    CGPoint centerPoint = CGPointMake(contentSize.width / 2, contentSize.height / 2);
    
    // center horizontally
    if (imgFrame.size.width <= boundsSize.width)
    {
        centerPoint.x = boundsSize.width / 2;
    }
    
    // center vertically
    if (imgFrame.size.height <= boundsSize.height)
    {
        centerPoint.y = boundsSize.height / 2;
    }
    self.imageView.center = centerPoint;
}

/** 记录当前的倍数 */
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    self.currentScale = scale;
}

@end
